package thesis.prototype;

import thesis.prototype.objects.ConnectPHP;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.TelephonyManager;

public class LocationUpdaterService extends Service {

	// private location objects
	static LocationManager locManager;
	static LocationListener locListener;
	static Location currentLocation;
	
	// constants
	private final int minTime = (int) (1000 * 60 * 1.5); //90000;
	private final int minDistance = 50;
	
	// DB Connectivity
	ConnectPHP DBConnection;
	String ownNumber;
		
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		return START_STICKY;
	}

	@Override
	public void onCreate()
	{
		locManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
		locListener = new LocationListener() {
		    public void onLocationChanged(Location location) {
		        // Called when a new location is found by the network location provider.
		        updateDBWithLocation(location);
		      }

		      public void onStatusChanged(String provider, int status, Bundle extras) {}

		      public void onProviderEnabled(String provider) {}

		      public void onProviderDisabled(String provider) {}
		    };
		    
		locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, locListener);
		
		DBConnection = ConnectPHP.getInstance();
		TelephonyManager teleManager =(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		ownNumber = teleManager.getLine1Number();
	}
	
	public void updateDBWithLocation(Location location)
	{
		currentLocation = location;
		DBConnection.putLocation(ownNumber, location.getLongitude(), location.getLongitude());
	}
	
	@Override
	public void onDestroy()
	{
		locManager.removeUpdates(locListener);
	}
	
	public static Location getCurrentLocation()
	{
		if(currentLocation == null)
		{
			Location temp = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			currentLocation = temp;
			return currentLocation;
		}
		return currentLocation;
	}
}
